<?php
namespace app\common\controller;

use org\Auth;
use think\Loader;
use think\facade\Cache;
use think\Controller;
use think\Db;
use think\facade\Session;

/**
 * 后台公用基础控制器
 * Class AdminBase
 * @package app\common\controller
 */
class ChannelBase extends Controller
{
    protected $channel_id = 0;
    protected function initialize()
    {
        parent::initialize();

        $this->checkAuth();
        $this->getMenu();

        $route = $this->request->routeInfo();
        $route_name = explode('/', $route['rule']);
        if(!empty($route['rule'])){
            if(count($route_name) <= 1){
                //默认进入数据统计页面
                $controller = "stat";
                $action = "index";
            }else{
                $controller = $route_name[1];
                $action = $route_name[2] ?? "index";
            }
        }else{
            $controller = Loader::parseName($this->request->controller());
            $action = Loader::parseName($this->request->action());
        }

        // 输出当前请求控制器（配合后台侧边菜单选中状态）
        $this->assign('controller', $controller);
        $this->assign('action', $action);

    }

    /**
     * 权限检查
     * @return bool
     */
    protected function checkAuth()
    {

        if (!Session::has('channel_id')) {
            $this->redirect('/channel/login');
        }
        $this->channel_id = Session::get('channel_id');
//        $module     = $this->request->module();
//        $controller = $this->request->controller();
//        $action     = $this->request->action();
//
//        // 排除权限
//        $not_check = ['channel/Index/index', 'channel/AuthGroup/getjson', 'channel/System/clear'];
//
//        if (!in_array($module . '/' . $controller . '/' . $action, $not_check)) {
//            $auth     = new Auth();
//            $channel_id = Session::get('channel_id');
//            if (!$auth->check($module . '/' . $controller . '/' . $action, $channel_id) && $channel_id != 1) {
//                $this->error('没有权限');
//            }
//        }
    }

    /**
     * 获取侧边栏菜单
     */
    protected function getMenu()
    {
        $menu     = [];
        $channel_id = Session::get('channel_id');
        $auth     = new Auth();

        $auth_rule_list = Db::connect("db_config_aiqi")->name('auth_rule')->where('status', 1)->order(['sort' => 'DESC', 'id' => 'ASC'])->select();

        foreach ($auth_rule_list as $value) {
//            if ($auth->check($value['name'], $channel_id) || $channel_id == 1) {
//                $menu[] = $value;
//            }
            $menu[] = $value;
        }
        $menu = !empty($menu) ? array2tree($menu) : [];

        $this->assign('menu', $menu);
    }
}